package com.tunnel.service.server;


import com.tunnel.common.config.ServerParsConfig;
import com.tunnel.common.config.server.ServiceConfig;

import com.tunnel.service.hendler.HttpHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;


/**
 * 启动一个对外暴露的http服务，用于接收http请求，转发给客户端
 */
public class HttpServer implements Server {
    ServerBootstrap serverBootstrap;
    // 创建事件循环组
    NioEventLoopGroup bossGroup;
    NioEventLoopGroup workerGroup;
    ServiceConfig serviceConfig;

    @Override
    public void init() {
        // todo

    }

    @Override
    public void shutdown() {
// todo
    }

    @Override
    public void start(ServiceConfig serviceConfig) throws InterruptedException {
        this.serviceConfig = serviceConfig;

        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        // 基础netty一套流程
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_RCVBUF, 16 * 1024);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //得到pipeline
                ChannelPipeline pipeline = ch.pipeline();
                // 解析http协议
                pipeline.addLast(new HttpServerCodec());
                pipeline.addLast(new HttpObjectAggregator(65536));
                // 处理转发请求
                pipeline.addLast(new HttpHandler());
            }
        });
        // 绑定端口数据
        ChannelFuture channelFuture = serverBootstrap.bind(serviceConfig.getHttpPort()).sync();
        //监听关闭
        channelFuture.channel().closeFuture().sync();
    }
}
